<template>
    <div>
        <div class="room-list-div-top"></div>
        <div class="room-list-div">
            <el-container style="height: 510px">
                <el-container>
                    <el-header>
                        <el-row>
                            <el-col :span="12">
                                <div style="text-align: left; font-size: 12px">
                                    <el-button type="primary" icon="el-icon-notebook-1" @click="game_rules()" :loading="loadingList">游戏规则</el-button>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div style="text-align: right; font-size: 12px">
                                    <el-button type="primary" icon="el-icon-s-order" @click="open_task" :loading="loadingList">查看身份/任务卡</el-button>
                                </div>
                            </el-col>
                        </el-row>
                    </el-header>

                    <el-main class="el-mian-config" v-loading="loadingList">
                        <el-row class="row-bg" :gutter="20">
                            <el-col v-for="(items, index) in player_list" :key="index" :span="6"
                                style="text-align: center;" :style="{'margin-top': set_style(index)}"
                                @click.native="playSound('click_one')">
                                <el-popover placement="top-start" trigger="click" width="200">
                                    <el-descriptions title="" direction="vertical" :column="2" border @click.native="playSound('click_one')">
                                        <el-descriptions-item label="YY/群昵称" :span="2">{{ items.nickname }}</el-descriptions-item>
                                        <el-descriptions-item label="角色昵称" :span="2" v-if="!!items.career_name">{{ items.career_name }}</el-descriptions-item>
                                        <el-descriptions-item label="职业">{{ items.career | optimizeDisplay }}</el-descriptions-item>
                                        <el-descriptions-item label="专职">{{ items.transfer | optimizeDisplay }}</el-descriptions-item>

                                        <el-descriptions-item label="状态">
                                            <el-tag type="info" v-if="rooms_info.room_status == 1 && items.status == 1" effect="dark">未抽卡</el-tag>
                                            <el-tag type="success" v-if="rooms_info.room_status == 1 && items.status == 2" effect="dark">等待开始</el-tag>
                                            <el-tag type="success" v-if="rooms_info.room_status == 2 && items.status == 3" effect="dark">未投票</el-tag>
                                            <el-tag type="warning" v-if="rooms_info.room_status == 2 && items.status == 4" effect="dark">已投票</el-tag>
                                            <el-tag type="info" v-if="items.career == ''" effect="dark" style="margin-left: 10px;">待选择角色</el-tag>
                                        </el-descriptions-item>
                                        <!-- <el-descriptions-item label="操作" v-if="rooms_info.room_status == 1 && player_info.master == 1 && items.player_code != player_info.player_code">
                                            <el-button type="danger" icon="el-icon-error" style="width: 100%;">强制退出赛事</el-button>
                                        </el-descriptions-item> -->
                                    </el-descriptions>
                                    <div slot="reference">
                                        <el-image v-if="!!items.cover" style="width: 80px; height: 80px" :src="items.cover"></el-image>
                                        <el-image v-else style="width: 80px; height: 80px" :src="require('@/assets/images/other/good.jpg')" class="null-img"></el-image>
                                        <p class="demonstration" :class="items.player_code == player_info.player_code? 'my-name-text': ''">{{ !!items.career_name ? items.career_name:items.nickname }}</p>
                                    </div>
                                </el-popover>
                            </el-col>
                        </el-row>
                    </el-main>
                </el-container>
            </el-container>
            
            <el-footer style="text-align: left; font-size: 12px; ">
                <div v-if="rooms_info.room_status == 1 && player_info.master != 1">
                    <el-tooltip class="item" effect="dark" content="冷却时间10S" placement="top">
                        <el-button style="width: 50%;" type="warning" icon="el-icon-monitor" @click="edit_rank()" :loading="loadingList" :disabled="disabled_career">选择角色</el-button>
                    </el-tooltip>
                    <el-button style="width: 46%" type="warning" icon="el-icon-back" @click="leave_room()" :loading="loadingList">退出房间</el-button>
                </div>
                <div v-if="rooms_info.room_status == 1 && player_info.master == 1">
                    <el-tooltip class="item" effect="dark" content="冷却时间10S" placement="top">
                        <el-button style="width: 25%;" type="warning" icon="el-icon-monitor" @click="edit_rank()" :loading="loadingList" :disabled="disabled_career">选择角色</el-button>
                    </el-tooltip>
                    <el-button style="width: 45%;" type="primary" icon="el-icon-video-play" @click="start_game()" :loading="loadingList">开始游戏</el-button>
                    <el-button style="width: 25%;" type="danger" icon="el-icon-error" @click="close_room()" :loading="loadingList">关闭房间</el-button>
                </div>

                <div v-if="rooms_info.room_status == 2 && player_info.status == 3">
                    <el-button style="width: 100%" type="primary" icon="el-icon-edit-outline" @click="start_voting()" :loading="loadingList">开始投票</el-button>
                </div>
                <div v-if="rooms_info.room_status == 3 && player_info.master != 1">
                    <el-button style="width: 100%" type="primary" icon="el-icon-connection" @click="game_panel()" :loading="loadingList">赛事面板</el-button>
                </div>
                <div v-if="rooms_info.room_status == 3 && player_info.master == 1">
                    <el-button style="width: 50%" type="primary" icon="el-icon-connection" @click="game_panel()" :loading="loadingList">赛事面板</el-button>
                    <el-button style="width: 46%;" type="danger" icon="el-icon-error" @click="close_room()" :loading="loadingList">关闭房间</el-button>
                </div>
            </el-footer>
        </div>

        <div class="room-list-div-bottom"></div>



        <!-- 游戏规则 -->
        <game-rule :LogingRule="logingRule" @MusicSound="playSound" @closeDialog="closeComponents"></game-rule>
        <!-- 选择卡牌 -->
        <table-sheet :DialogingTable="logingTable" :RoomCode="query.room_code" @MusicSound="playSound" @closeDialog="closeComponents"></table-sheet>
        <!-- 加载动画 -->
        <uio-loading :LogingMake="logingMake"></uio-loading>
        <!-- 身份、任务卡片 -->
        <uio-card :LogingCard="logingCard" :PlayerInfo="player_info" @MusicSound="playSound" @closeDialog="closeComponents"></uio-card>
        <!-- 编队(现在是选择参赛角色) -->
        <uio-rank :LogingRank="logingRank" :RoomCode="query.room_code" :PlayerInfo="player_info" @MusicSound="playSound" @closeDialog="closeComponents"></uio-rank>
        <!-- 投票 -->
        <uio-vote :LogingVote="logingVote" :RoomCode="query.room_code" :PlayerCode="player_info.player_code" :PlayerList="player_list" @MusicSound="playSound" @closeDialog="closeComponents"></uio-vote>
        <!-- 比赛结果 -->
        <uio-response :LogingPanel="logingPanel" :RoomCode="query.room_code" @MusicSound="playSound" @closeDialog="closeComponents"></uio-response>
    </div>
</template>
<script>
// 比赛规则
import gameRule from '@/components/common/assembly/make/game-rule.vue';
// 抽卡
import tableSheet from '@/components/common/assembly/sheet/table.vue';
// 动画
import uioLoading from '@/components/common/assembly/make/loading.vue';
// 身份卡
import uioCard from '@/components/common/assembly/sheet/card.vue';
// 编辑队伍
import uioRank from '@/components/common/assembly/operate/rank.vue';
// 投票
import uioVote from '@/components/common/assembly/operate/table-vote.vue';
// 比赛结果
import uioResponse from '@/components/common/assembly/operate/response.vue';
export default {
    name: 'gameRoom',
    data() {
        return {
            loadingList: false,

            logingRule: false,
            logingTable: false,
            logingMake: false,
            logingCard: false,
            logingRank: false,
            logingVote: false,
            logingPanel: false,
            disabled_career: false,

            rooms_info: {
                // status 0:房间已被房主关闭，1:正常没有开始，2:已经开始可以投票了，3:游戏结束可以显示所有信息了，4:房间异常超级管理员禁用了，
            },
            player_info: {},
            player_list:[],

            query: this.$route.query,

            // socket_address: 'ws://127.0.0.1:1998',
            socket_address: 'wss://socket.ivsheng.com/ws',
            socket: {}
        };
    },
    filters: {
        optimizeDisplay(data) {
            if (!data) {
                return '未选择';
            } else {
                return data;
            }
        },
    },
    created() {
        // 没有登陆 或者登陆失效，返回大厅，让他去登陆
        if (!this.$store.state.users_status || !this.$route.query.room_code) {
            this.$router.push('/');
        } else {
            // 都没有问题，先链接socket 拿到 client_id
            this.establishConnection();
        }
    },
    methods: {
        establishConnection() {
            // 定义
            let _this = this;
            this.socket = new WebSocket(this.socket_address);
            // 连接失败
            this.socket.onerror = function () {
                _this.$notify.error({ title: '错误', message: '链接服务器失败，请联系管理员【socket:onerror】' });
            };
            // 连接成功
            this.socket.onopen = function () {
                console.log('socket open success:', _this.socket_address);
            };
            
            // 监听并且判断消息类型
            this.socket.onmessage = function(e){
                let data = JSON.parse(e.data);
                let type = data.type || '';
                
                switch(type){
                    case 'init':		//初始化
                        _this.personal(data.client_id);
                        break;

                    case 'room_info':		// 房间信息
                        _this.rooms_info = data.content;
                        if (_this.rooms_info.room_status == 2) {
                            _this.playSound('combustion');
                            _this.$notify.success({ title: '赛事开启', message: '请按照卡牌任务进行比赛', duration: 0});
                        } else if (_this.rooms_info.room_status == 0) {
                            _this.$alert('房间已经被房主关闭，请回到大厅重新寻找队伍', '赛事关闭', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    _this.$router.push('/')
                                }
                            });
                        }
                        break;
                    
                    case 'player_info':		// 玩家列表
                        _this.player_info = data.content;
                        break;
                    
                    case 'player_list':		// 玩家列表
                        _this.player_list = data.content;
                        break;
                        
                    case 'end_game':		// 游戏结束
                        _this.game_panel();
                        break;

                    case 'ping':		//初始化
                        _this.socket.send('{"type":"pong"}');
                        break;
                        
                    default :
                        console.log('未定义类型信息：', data);
                }
            };
        },
        personal(client_id) {
            if (!!client_id) {
                this.loadingList = true;
                this.$post('/api/rooms-player/info.html', {
                    room_code: this.query.room_code,
                    client_id: client_id,
                }).then(res => {
                    if (res.code == 200) {
                        this.player_info = res.data;
                        if (this.player_info.status == '1') {
                            this.logingTable = true;
                        }
                    } else {
                        this.$notify.error({ title: '', message: res.msg});
                    }
                    this.loadingList = false;
                }).catch(err => {
                    this.loadingList = false;
                    console.log(err);
                });
            }
        },
        game_rules() {
            // 游戏规则
            this.playSound('click_two');
            this.logingRule = true;
        },
        edit_rank() {
            this.playSound('click_two');
            this.logingRank = true;
        },
        start_game() {
            this.playSound('click_two');
            // 关闭房间
            this.$confirm('此操作将开启赛事，是否继续?', 'Notice', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.playSound('click_two');
                this.$post('/api/rooms/start.html', {room_code: this.query.room_code}).then(res => {
                    if (res.code == 200) {
                        this.playSound('close');
                        this.$notify.success({ title: '', message: "游戏开始啦"});
                    } else {
                        this.$notify.error({ title: '', message: res.msg});
                    }
                    this.loadingList = false;
                }).catch(err => {
                    this.loadingList = false;
                    console.log(err);
                });
            });
        },
        start_voting() {
            // 开始投票
            this.playSound('click_two');
            this.logingVote = true;
        },
        close_room(){
            this.playSound('click_two');
            // 关闭房间
            this.$confirm('此操作将关闭房间，并且清除出所有选手，是否继续?', 'Notice', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.playSound('click_two');
                this.$post('/api/rooms/close.html', {room_code: this.query.room_code}).then(res => {
                    if (res.code == 200) {
                        this.playSound('close');
                        this.$notify.info({ title: '', message: "房间已成功关闭"});
                        this.$router.push('/')
                    } else {
                        this.$notify.error({ title: '', message: res.msg});
                    }
                    this.loadingList = false;
                }).catch(err => {
                    this.loadingList = false;
                    console.log(err);
                });
            });
        },
        leave_room(){
            this.playSound('click_two');
            // 退出房间
            this.$confirm('确认放弃本次比赛?', 'Notice', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.playSound('click_two');
                this.$post('/api/rooms-player/leave.html', {room_code: this.query.room_code}).then(res => {
                    if (res.code == 200) {
                        this.playSound('close');
                        this.$notify.info({ title: '', message: "已成功放弃本次比赛"});
                        this.$router.push('/')
                    } else {
                        this.$notify.error({ title: '', message: res.msg});
                    }
                    this.loadingList = false;
                }).catch(err => {
                    this.loadingList = false;
                    console.log(err);
                });
            });
        },
        game_panel(){
            // 比赛结束，查看面板
            this.playSound('open');
            this.logingPanel = true;
        },
        open_task() {
            this.playSound('click_two');
            this.logingCard = true;
        },
        playSound(keyword) {
            this.$parent.playSound(keyword);
        },
        closeComponents(key, value, play_sound) {
            console.log("GameRoom - Page CloseComponents",  key, value, play_sound)
            let _this = this;
            if (!!play_sound) {
                _this.playSound(play_sound);
            } else {
                if (value) {
                    _this.playSound('open');
                } else {
                    _this.playSound('close');
                }
            }
            // 不管是啥 优先赋值
            _this[key] = value;

            // 判断是否特殊条件
            if (key == 'logingTable' && !value) {
                _this.logingMake = true;
                _this.playSound('close');
                setTimeout(function () {
                    
                    // 关闭动画
                    _this.logingMake = false;
                    // 显示身份卡牌
                    _this.logingCard = true;
                }, 2000);
            } else if (key == 'logingRank' && !value) {
                _this.disabled_career = true;
                setTimeout(function () {
                    _this.disabled_career = false;
                }, 10000);
            }
        },
        set_style(index) {
            if (index <= 3) {
                return '0px';
            } else {
                return '20px';
            }
        }
    },
    components: { gameRule, tableSheet, uioLoading, uioCard, uioRank,uioVote, uioResponse },
};
</script>
<style scoped>
.el-header {
    border-radius:40px 40px 0px 0px !important;
    line-height: 60px;
}

.el-footer{
    border-radius:0px 0px 40px 40px;
    color: #333;
    line-height: 60px;
}
.room-list-div-top {
    width: 20%;
    height: 30px;
    min-width: 100px;
    margin: auto;
    background-image: url('../../../assets/images/other/bakal/border/4.png');
}


.room-list-div {
    border-radius: 10px;
    width: 32%;
    height: 60%;
    min-width: 500px;
    min-height: 500px;
    margin: auto;
    background-image: url('../../../assets/images/background/caihai-black.jpeg');
}

.room-list-div-bottom {
    width: 20%;
    height: 30px;
    min-width: 100px;
    margin: auto;
    background-image: url('../../../assets/images/other/bakal/border/3.png');
    background-size: cover;
}

/* .room-list-button-images-div {
    position: relative;
    width: 130px;
    margin: auto;
    transition: color 3s ease;
}
.room-list-button-images-div:hover {
    .room-list-button-images {
        content: url('../../../assets/images/button/25.png');
    }
    .room-list-button-text {
        color: #c0c0c0;
    }
} */
/* .room-list-button-text {
    user-select: none;
    z-index: 1;
    position: absolute;
    top: 8px;
    left: 18px;
    font-size: 16px;
    color: #deb887;
    transition: color 3s ease;
} */

.el-mian-config{
    user-select: none;
    border-radius: 10px;
    background-color: #fff;
} 
.row-bg{
    padding: 20px;
}

.null-img{
    filter: grayscale(100%);
}

.user-card-col{
    /* background-color: aqua; */
}

</style>

